/*
 * @Author: N0ts
 * @Date: 2021-10-19 13:25:56
 * @LastEditTime: 2021-10-29 10:32:45
 * @Description: main
 * @FilePath: /Web/js/main.js
 * @Mail：mail@n0ts.cn
 */

// 从 Vue 中引入
const { createApp, ref } = Vue;

// Hooks
import user from "./hooks/user.js";
import bar from "./hooks/bar.js";
import access from "./hooks/access.js"
import notify from "./hooks/notify.js";

// 是否重制
let reload = false;

// 创建 Vue 应用
const App = createApp({
    setup() {
        let apiLock = ref(false);

        function logout() {
            notify("注销成功！即将自动返回登陆", "success");
            clearLocal();
        }

        function clearLocal() {
            window.localStorage.removeItem("userInfo");
            setTimeout(() => {
                window.location.reload();
            }, 3000);
        }

        // axios 请求拦截
        axios.interceptors.request.use(
            function (config) {
                // 转圈圈
                apiLock.value = true;
                // token 存在则携带
                let token = window.localStorage.getItem("userInfo");
                if (token) {
                    config.headers.Authorization = JSON.parse(token).token;
                }
                return config;
            },
            function (error) {
                return Promise.reject(error);
            }
        );

        // axios 响应拦截
        axios.interceptors.response.use(
            function (response) {
                // 转圈圈
                apiLock.value = false;
                response = response.data;
                return response;
            },
            function (error) {
                // 转圈圈
                apiLock.value = false;
                // 模型注解报错
                if(error.toString().includes("status code 400")) {
                    notify(error.response.data.errors.mail[0], "warning");
                    return Promise.reject(error);
                }
                if(reload) {
                    return;
                }
                reload = true;
                // 如果token过期
                if(!error.toString().includes("status code 401")) {
                    return Promise.reject(error);
                }
                clearLocal();
                notify("登陆已过期，即将重新登录", "error");
                return Promise.reject(error);
            }
        );
        return {
            apiLock,
            logout,
            ...user(),
            ...bar(),
            ...access()
        };
    }
});

// 使用 ElementUI
App.use(ElementPlus);

// 挂载到根节点
App.mount("#app");
